<template>
  <div class="talks_info">
    <TalksItem :talksItem="talks" />
    <Comment
      ref="messageCommentRef"
      :comments="comments"
      @onComment="onComment"
      @onReply="onReply"
    />
  </div>
</template>

<script setup>
  import { onBeforeMount, reactive, ref } from 'vue'
  import { useRoute } from 'vue-router'
  import TalksItem from './TalksItem.vue'
  import Comment from '@/components/Comment.vue'
  import { queryDetailByIdRequest } from '@/network/api/talks'
  import {
    messageCommentRequest,
    messageReplyRequest,
  } from '@/network/api/comment'
  import Message from 'vue-m-message'
  import formatComment from '@/utils/comments'
  import { localCache } from '@/utils/cache'
  import useUserStore from '@/store/userStore'

  const userStore = useUserStore()
  const route = useRoute()
  const talks = reactive({
    content: null,
    author: null,
    avatar: null,
    commentCount: null,
    createAt: null,
  })
  const comments = ref([])
  const messageCommentRef = ref(null)
  onBeforeMount(async () => {
    const result = await queryDetailByIdRequest(route.params.id)
    // console.log(result)
    talks.content = result.result.message.content
    talks.author = result.result.message.author
    talks.avatar = result.result.message.avatar
    talks.commentCount = result.result.message.commentCount
    talks.createAt = result.result.message.createAt
    const newComments = formatComment(result.result.comments)
    // console.log(newComments)
    comments.value = newComments
  })
  const onComment = async comment => {
    console.log('message-comment')
    if (!userStore.isLogin || !localCache.getCache('user'))
      return Message.warning('请先登录~')
    if (!comment) return Message.warning('未检测到文字~')
    const res = await messageCommentRequest(comment, route.params.id)
    Message.success(res.msg)
    // 更新视图
    const result = await queryDetailByIdRequest(route.params.id)
    talks.commentCount = result.result.message.commentCount
    comments.value = formatComment(result.result.comments)
    messageCommentRef.value.reset()
  }
  const onReply = async (reply, id) => {
    console.log('message-reply')
    if (!userStore.isLogin || !localCache.getCache('user'))
      return Message.warning('请先登录~')
    if (!reply) return Message.warning('未检测到文字~')
    const res = await messageReplyRequest(reply, route.params.id, id)
    Message.success(res.msg)
    // 更新视图
    const result = await queryDetailByIdRequest(route.params.id)
    talks.commentCount = result.result.message.commentCount
    console.log(result)
    console.log(formatComment(result.result.comments))
    comments.value = formatComment(result.result.comments)
  }
</script>

<style lang="less" scoped>
  @media only screen and (min-width: 991px) {
    .talks_info {
      width: 78%;
    }
  }
  @media only screen and (max-width: 990px) {
    .talks_info {
      width: 100%;
    }
  }
</style>
